package com.android.lovely.ui.activity

import android.os.Bundle
import androidx.core.view.isGone
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.android.lovely.R
import com.android.lovely.api.service.userService
import com.android.lovely.databinding.ActivityOptimizationBinding
import com.android.lovely.ext.windowBackgroundNav
import com.android.lovely.ext.windowBackgroundStatus
import com.android.lovely.framework.BaseActivity
import com.android.lovely.framework.UIController.showToast
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.ui.adapter.OptimizationAdapter
import com.google.android.flexbox.FlexboxLayoutManager
import com.kotlin.extensions.context.ContextExt.startPage
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable

class OptimizationActivity : BaseActivity<ActivityOptimizationBinding>() {

    private val adapter by lazy {
        OptimizationAdapter().apply {
            onItemClick = { _, _ ->
                mBinding.disable.isGone = mBinding.content.text.toString().isNotEmpty()
            }
        }
    }

    private val userId by lazy {
        intent.getIntExtra("user_id", -1)
    }

    private val aiId by lazy {
        intent.getIntExtra("ai_id", -1)
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.llTop.addStatusBarMarginTop()
        mBinding.items.adapter = adapter
        mBinding.items.layoutManager = FlexboxLayoutManager(this)
        mBinding.back.clickable {
            onBackPressedDispatcher.onBackPressed()
        }
        mBinding.orderReport.clickable {
            startPage<RechargeBackActivity>("bot_id" to userId)
        }
        mBinding.content.addTextChangedListener {
            mBinding.contentNum.text = "${it?.length ?: 0}/800"
            mBinding.disable.isGone = adapter.currentOptimization > -1 && mBinding.content.text.toString().isNotEmpty()
        }
        mBinding.email.addTextChangedListener {
            mBinding.mailNum.text = "${it?.length ?: 0}/100"
        }
        mBinding.submit.clickable {
            submit()
        }
    }

    private fun submit() {
        lifecycleScope.launchWithLoading {
            userService.reportV2(
                mapOf(
                    "bot_id" to userId,
                    "reason_content" to adapter.currentOptimization,
                    "detail" to mBinding.content.text.toString(),
                    "type" to if (aiId != -1) 3 else 1,
                    "reason_id" to adapter.currentOptimization,
                    "task_id" to aiId,
                    "email" to mBinding.email.text.toString()
                )
            )
            showToast(getString(R.string.report_success))
            finish()
        }.onError {
            showToast(getString(R.string.report_failure))
        }
    }
}